﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NullCommander
{
    public partial class frmFileInfo : Form
    {
        private const String REG_PATH = @"HKEY_CLASSES_ROOT\";
        private String path;
        
        public frmFileInfo(String path)
        {
            InitializeComponent();

            this.path = path;

        }

        private String GetStrFromRegistry(String key, String value)
        {
            return Registry.GetValue(key, value, String.Empty) as String;
        }

        private void GetInfo(String ext, out String description, out String app)
        {
            description = String.Format("Файл \"{0}\"", ext.ToUpper());
            app = String.Empty;
            var str = GetStrFromRegistry(REG_PATH + ext, String.Empty);
            if (String.IsNullOrEmpty(str))
                return;
            description = GetStrFromRegistry(REG_PATH + str, String.Empty);
            str = GetStrFromRegistry(REG_PATH + str + @"\shell\open\command", String.Empty);
            if (String.IsNullOrEmpty(str))
                return;
            var temp = str.Split(new[] { '"' }, StringSplitOptions.RemoveEmptyEntries);
            if (temp.Length > 0)
                app = Path.GetFileName(temp[0]);
        }

        private void frmFileInfo_Load(object sender, EventArgs e)
        {
            try
            {
                var info = new FileInfo(path);
                var icon = Icon.ExtractAssociatedIcon(info.FullName);
                pboxIcon.Image = icon.ToBitmap();
                lblName.Text = info.Name;

                String description, app, ext;
                ext = Path.GetExtension(info.FullName);
                GetInfo(ext, out description, out app);
                lblExtAndType.Text = String.Format("{0} ({1})", description, ext);
                lblApplication.Text = app;

                var size = info.Length;
                lblSize.Text = ClassHelpers.FileSizeToString(size);
                var date = info.CreationTime;
                lblDateCreation.Text = date.ToString(ClassHelpers.DATE_TIME_FORMAT);
                date = info.LastWriteTime;
                lblDateModification.Text = date.ToString(ClassHelpers.DATE_TIME_FORMAT);
                chkReadOnly.Checked = (info.Attributes & FileAttributes.Hidden) != 0;
            }
            catch (Exception)
            {
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
